package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    //一行一行读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new GuliException(20001,"文件数据为空");
        }

        EduSubject oneEduSubject = this.existOneSubject(subjectData.getOneSubjectName(), eduSubjectService);
        if (oneEduSubject == null) {
            oneEduSubject = new EduSubject();
            oneEduSubject.setParentId("0").setTitle(subjectData.getOneSubjectName());
            eduSubjectService.save(oneEduSubject);
        }
        //获取一级分类id值
        String pid = oneEduSubject.getId();
        EduSubject twoEduSubject = this.existTwoSubject(subjectData.getTwoSubjectName(), eduSubjectService,pid);
        if (twoEduSubject == null) {
            twoEduSubject = new EduSubject();
            twoEduSubject.setParentId(pid).setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(twoEduSubject);
        }

    }

    //判断一级分类不能重复添加
    private EduSubject existOneSubject(String name,EduSubjectService eduSubjectService){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(String name,EduSubjectService eduSubjectService,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
